﻿using System;
using System.Web.UI;

namespace Trentacular.SharePoint.Web.UI.WebParts
{
    /// <summary>
    /// Base class to be inherited by Web Parts that wrap a User Control.
    /// </summary>
    public abstract class UserControlWebPart : WebEditableWebPart
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UserControlWebPart"/> class.
        /// </summary>
        /// <param name="userControlVirtualPath">The user control virtual path.</param>
        public UserControlWebPart(string userControlVirtualPath)
        {
            this.UserControlVirtualPath = userControlVirtualPath;
        }

        /// <summary>
        /// Gets the user control virtual path.
        /// </summary>
        /// <value>The user control virtual path.</value>
        protected string UserControlVirtualPath { get; private set; }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use
        /// composition-based implementation to create any child controls they contain
        /// in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                var userControl = Page.LoadControl(this.UserControlVirtualPath);
                Controls.Add(userControl);
            }
            catch (Exception e)
            {
                Controls.Add(new LiteralControl(e.Message));
                //Log.Error(e.Message, e);
            }

            base.CreateChildControls();
        }
    }
}
